package jm.nj.demo14mian.demo02;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.stream.Stream;

/*
* UDP接收端
*
* 1.创建DatagramSocket,DatagramPacket
* 2.接收数据到存储DatagramPacket对象中
* 3.获取DatagramPacket对象的内容
* 4.释放
* */
public class UDPreceive {
    public static void main(String[] args) throws IOException {
        //创建DatagramSocket对象并指定端口
        DatagramSocket receiveSocket = new DatagramSocket(12306);
        //创建DatagramPacket 对象创建一个空仓库
        byte[] buffer = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buffer,1024);
        //接收数据存储到DatagramPacket对象中
        receiveSocket.receive(dp);

        //______________________拆包

        //获取DatagramPacket对象的内容
        //谁发来的数据getAddress();
        InetAddress ipAddress  = dp.getAddress();

        String ip = ipAddress.getHostAddress();//获取ip

        //发来什么数据getData();
        byte[] data = dp.getData();

        //数据长度
        int length = dp.getLength();
        System.out.println(length);
        System.out.println(data.length);

        //显示数据
        String dataStr = new String(data,0,length);
        System.out.println("ip地址:"+ip+"数据是"+dataStr);

        System.out.println(receiveSocket.getLocalPort());

        //释放
        receiveSocket.close();









    }
}
